package com.jk.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.dao.UserDao;
import com.jk.entity.*;
import com.jk.utils.Md5UUIDSaltUtil;
import com.jk.utils.MsgUtil;
import com.jk.utils.SendCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings("all")
public class UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<UserEntity> getYhList(UserEntity user) {
        return userDao.getYhList(user);
    }

    public List<UserEntity> getHyList(UserEntity user) {
        return userDao.getHyList(user);
    }

    public void deleteUserById(Integer id) {
        userDao.deleteUserById(id);
    }

    public List<ProductEntity> getUserProject(String ids) {
        String[] as = ids.split(",");
        List<ProductEntity> list=new ArrayList<>();
        for (int i = 0; i < as.length; i++) {
            ProductEntity userProject = userDao.getUserProject(as[i]);
            list.add(userProject);
        }
        return list;
    }

    public UserEntity getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    public void updateUser(UserEntity user) {
        userDao.updateUser(user);
    }

    public List<UserEntity> getYhList1(UserEntity user) {
        return  userDao.getYhList1(user);
    }

    public List<ComboEntity> getComboList(String ids) {
        String[] as = ids.split(",");
        List<ComboEntity> list=new ArrayList<>();
        for (int i = 0; i < as.length; i++) {
            ComboEntity conbo= userDao.getComboList(as[i]);
            list.add(conbo);
        }
        return list;
    }

    /**
     * @description: 发短信
     * @author: mhj
     * @date: 2022/11/9 11:33
     * @param: [phone]
     * @return: java.util.Map
     **/
    public Map sendCode(String phone) {
        String key="code"+phone;

        JSONObject obj = SendCode.sendCode(phone);
        int code = obj.getIntValue("code");

        if(code!=200){
            return MsgUtil.returnMsg(251,"发送失败",null);
        }
        //获取发送的验证码
        String round = obj.getString("obj");
        //存入Redis,设置60秒过期
        redisTemplate.opsForValue().set(key,round,6000,TimeUnit.SECONDS);
        return MsgUtil.returnMsg(200,"发送成功,请注意查收",null);
    }


    public Map registerUser(UserEntity userEntity) {
        String key="code"+userEntity.getUserPhone();
        if(!redisTemplate.hasKey(key)){
            return MsgUtil.returnMsg(253,"验证码已过期",null);
        }
        String code2 = (String) redisTemplate.opsForValue().get(key);
        if(!code2.equals(userEntity.getCode())){
            return MsgUtil.returnMsg(252,"验证码错误，请重新获取",null);
        }else{
            //加盐,并将加过盐的密码 和盐重新存入数据库中
            String salt = Md5UUIDSaltUtil.getSalt();
            //自己想搞什么搞什么 加密
            String mySalt=salt.substring(0,5);

            String password = Md5UUIDSaltUtil.createMd5Code(userEntity.getUserPwd()+mySalt);
            userEntity.setUserPwd(password);
            userEntity.setSalt(salt);
            userEntity.setUserType(3);
            userDao.insert(userEntity);
        }
//        redisTemplate.delete(key);
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("userPhone",userEntity.getUserPhone());
        UserEntity user = userDao.selectOne(wrapper);


        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(token, userEntity.getUserPhone(), 3600, TimeUnit.SECONDS);
        user.setToken(token);
        user.setUserPwd(userEntity.getUserPwd());
        return MsgUtil.returnMsg(200,"恭喜成功注册极美",user);
    }




    public Map loginuser(UserEntity userEntity) {

        //相当于select * from user where account='${username}'
        QueryWrapper<UserEntity> wrapper=new QueryWrapper<>();
        wrapper.eq("userPhone",userEntity.getUserPhone());
        //user即为查询结果
        UserEntity staff = userDao.selectOne(wrapper);


        if (staff == null) {
            return MsgUtil.returnMsg(250,"账号错误",null);
        } else {
            String salt = staff.getSalt();
            String mySalt = salt.substring(0, 5);
            String md5Code = Md5UUIDSaltUtil.createMd5Code(userEntity.getUserPwd() + mySalt);
            if (!staff.getUserPwd().equals(md5Code)) {
                return MsgUtil.returnMsg(251, "密码错误", null);
            } else {
                //通过UUID生成token字符串,并将其以string类型的数据保存在redis缓存中，key为token，value为username
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                redisTemplate.opsForValue().set(token, userEntity.getUserPhone(), 3600, TimeUnit.SECONDS);
                staff.setToken(token);
                staff.setUserPwd(userEntity.getUserPwd());
                return MsgUtil.returnMsg(200, "登陆成功", staff);
            }
        }
    }

    public void updateSetting(ReceEntity rece) {
        userDao.updateSetting(rece.getReceId());
        userDao.upSet(rece.getReceId());
    }

    public void updateDefa() {
        userDao.updateDefa();
    }

    public void insertRece(ReceEntity rece) {
        userDao.insertRece(rece);
    }

    public List<AddEntity> getAddress() {
        List<AddEntity> list=new ArrayList<>();
        List<ReceEntity> address = userDao.getAddress();
        for (ReceEntity receEntity : address) {
            AddEntity add=new AddEntity();
            add.setId(receEntity.getReceId().toString());
            add.setName(receEntity.getReceName());
            add.setTel(receEntity.getRecePhone());
            add.setAddress(receEntity.getReceProvince()+receEntity.getReceCity()+receEntity.getReceCounty()+receEntity.getReceDetail());
            if(receEntity.getIsDefault()==2){
                add.setIsDefault(true);
            }else if(receEntity.getIsDefault()==1){
                add.setIsDefault(false);
            }
            list.add(add);
        }
        return list;
    }

    public List<FunctionEntity> getFunList() {
        return  userDao.getFunList();
    }


    public List<ComboEntity> getComList() {
        return  userDao.getComList();
    }

    public List<ProductEntity> getProList() {
        return  userDao.getProList();
    }


    public UserEntity userlist(Integer userId) {
        return userDao.selectById(userId);
    }

    public void getupdate(UserEntity userEntity) {

        userDao.updateById(userEntity);
    }

    //根据手机号查询
    public UserEntity selectUser(UserEntity userEntity) {
        String userPhone = userEntity.getUserPhone();
        return userDao.selectUser(userPhone);
    }

    @Autowired
    private MongoTemplate mongoTemplate;
    public List<OrderEntity> getOrderList(OrderEntity orderEntity) {
        Query query = new Query();
        query.addCriteria(Criteria.where("orderType").is(orderEntity.getOrderType()));
        query.addCriteria(Criteria.where("userId").is(orderEntity.getUserId()));
        List<OrderEntity> orderEntities = mongoTemplate.find(query, OrderEntity.class);
        return orderEntities;
    }

    public void getpwdupdate(UserEntity userEntity) {
        //加盐,并将加过盐的密码 和盐重新存入数据库中
        String salt = Md5UUIDSaltUtil.getSalt();
        //自己想搞什么搞什么 加密
        String mySalt=salt.substring(0,5);

        String password = Md5UUIDSaltUtil.createMd5Code(userEntity.getUserPwd()+mySalt);
        userEntity.setUserPwd(password);
        userEntity.setSalt(salt);
        userDao.updateById(userEntity);
    }

    ///////
    public void updateOrderList(UserEntity user) {
        userDao.updateOrderList(user);
    }



}
